package com.jieclouds.util;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Base64;
import java.util.Locale;

import static java.security.MessageDigest.getInstance;

public class DjApi {
    private static final String DJI_APP_KEY = "e_qgPXstEnDjarCZM_Sw9";//大疆智图API的APP Key
    private static final String DJI_SECRET_KEY = "Dr6qku6mKyGGk8qSBNfmoHPiBr1YOpRQ";//大疆智图API的Secret Key
    private static final String HOST = "https://openapi-cn.dji.com";
    /*
        URL 大疆智图API 接口请求地址
        payload 请求参数，如果不需要请求参数，请为空字符串
        lowerMethod 请求方法，小写字母  get/post/put/delete
     */
    public static JSONObject AccessDJ(String URI, String payload, String lowerMethod) {
        try {
            String url = HOST + URI;
            String date = getFormattedDate();
            String digest = getDigest(payload);
            String requestSignature = calculateSignature(date, lowerMethod, URI, digest);
            HttpRequest request = null;
            if(lowerMethod.equals("post")){// delete和post请求还未测试 根据需求进行添加
                request = HttpRequest.post(url);
            }else if(lowerMethod.equals("get")){
                request = HttpRequest.get(url);
            }
            request.header("Date", date)
                    .header("Digest", "SHA-256=" + digest)
                    .header("Authorization", "hmac username=\"" + DJI_APP_KEY + "\", algorithm=\"hmac-sha256\", headers=\"date @request-target digest\", signature=\"" + requestSignature + "\"")
                    .header("Content-Type", "application/json;charset=UTF-8");
            if (!payload.isEmpty()) {
                request.body(payload);
            }
            HttpResponse response = request.execute();
            if (response.isOk()) {
                System.out.println("response.body() = " + response.body());
                return JSONUtil.parseObj(response.body());
            } else {
                System.out.println("HTTP error code: " + response.getStatus());
                System.out.println("response = " + response);//查看失败原因
                return null;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    private static String getFormattedDate() {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("EEE, dd MMM yyyy HH:mm:ss 'GMT'", Locale.US)
                .withZone(ZoneId.of("GMT"));
        return formatter.format(ZonedDateTime.now(ZoneId.of("GMT")));
    }
    private static String getDigest(String data) throws NoSuchAlgorithmException {
        return Base64.getEncoder().encodeToString(getInstance("SHA-256").digest(data.getBytes(StandardCharsets.UTF_8)));
    }

    private static String calculateSignature(String date, String method, String uri, String digest) throws NoSuchAlgorithmException, InvalidKeyException {
        String content = "date: " + date + "\n@request-target: " + method + " " + uri + "\ndigest: SHA-256=" + digest;
        Mac hmacSha256 = Mac.getInstance("HmacSHA256");
        hmacSha256.init(new SecretKeySpec(DJI_SECRET_KEY.getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
        return Base64.getEncoder().encodeToString(hmacSha256.doFinal(content.getBytes(StandardCharsets.UTF_8)));
    }

    public static final String URI_TOKEN = "/terra-rescon-be/v2/store/obtain_token";
    public static void main(String[] args) {
        JSONObject accessToken = getAccessToken();
        System.out.println(accessToken);
    }
    public static JSONObject getAccessToken() {
        return AccessDJ(URI_TOKEN, "","post");
    }


}
